﻿using System;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Web;
using System.Web.UI;
using KPIS.GERP.GBMS.APP_UI.Common;
using KPIS.GERP.GBMS.IBLL;
using KPIS.GERP.GBMS.BLL;
using KPIS.GERP.GBMS.MODEL;
using KPIS.GERP.GHRMS.BLL;
using Telerik.Web.UI;

namespace KPIS.GERP.GBMS.MasterPage
{
    public partial class MasterPage : System.Web.UI.MasterPage
    {
        private UserBLL userBLL = new UserBLL();
        private EmployeeBLL empBLL = new EmployeeBLL();
        private MessageSend.MessageSend send = new MessageSend.MessageSend();
        private ISystemMenuBLL bll = new SystemMenuBLL();
        private SystemControlBLL scBLL = new SystemControlBLL();
        private static string strServerName;
        private SsMng ssMng = new SsMng();
        private APP_UI.Common.Main main = new Main();
        private HideMenuBy hideMenuBy = HideMenuBy.Hide;

        public enum HideMenuBy { Color, Hide };

        protected void Page_Load(object sender, EventArgs e)
        {
            if (GetLocalResourceObject("ซ่อนด้วย") as string == "Color")
            {
                hideMenuBy = HideMenuBy.Color;
            }

            strServerName = Request.Url.Host + (ConfigurationSettings.AppSettings["SubSystem"].ToString().Length > 0
                                                    ? "/" + ConfigurationSettings.AppSettings["SubSystem"].ToString()
                                                    : "");

            if (!IsPostBack)
            {
                PanelHeader.BackImageUrl = "~/App_UI/Image/" + ConfigurationSettings.AppSettings["Header"].ToString();
                HttpCookie cookieUserDetail = Request.Cookies["UserDetail"];


                if (cookieUserDetail != null && 
                    !string.IsNullOrEmpty(cookieUserDetail["UserSeq"]) && 
                    Convert.ToString(Session["EmpSeq"]) != Convert.ToString(cookieUserDetail["EmpSeq"]))
                {
                    var empSeq = cookieUserDetail["EmpSeq"];
                    
                    // Employeee Full Name has problem encoding because of cookie share each module may difference in Default Encoding, 
                    // resolve by load from database directly
                    DataRowCollection dr = empBLL.ListEmployeeBySeq(empSeq).Rows;
                    if(dr.Count == 0)
                    {
                        throw new Exception("Not found Employee of EmpSeq("+empSeq+")");
                    }
                    var userName = dr[0]["full_name"] as string;//cookieUserDetail["UserName"];
                    var userSeq = cookieUserDetail["UserSeq"];
                    var workingJobSiteSeq = cookieUserDetail["WorkingJobSiteSeq"];
                    var height = cookieUserDetail["Height"];

                    Session["UserSeq"] = userSeq;
                    Session["EmpSeq"] = empSeq;
                    Session["UserName"] = userName;
                    Session["WorkingJobSiteSeq"] = workingJobSiteSeq;
                    Session["Height"] = height;

                    ssMng.SetLoginSession(userSeq, empSeq, userName, workingJobSiteSeq, height);
                     
                    //DataRowCollection drc = userBLL.LoginByUserSeq(Convert.ToString(Session["UserSeq"])).Tables[0].Rows;

                    //if (drc.Count > 0)
                    //{
                    //    string userStatus = drc[0]["user_status"].ToString();

                    //    if (userStatus == SystemInfo._RejectStatus)
                    //    {
                    //        //RadManager1.Alert("รอการตรวจสอบจากผู้ดูแลระบบ");
                    //    }
                    //    else if (userStatus == SystemInfo._WorkRecordStatus)
                    //    {
                    //        ssMng.SetLoginSession(drc[0]["user_seq"].ToString(),
                    //            drc[0]["emp_seq"].ToString(),
                    //            drc[0]["user_name"].ToString(),
                    //            LoadEmployees(drc[0]["emp_seq"].ToString()),
                    //            cookieUserDetail["Height"]);
                    //    }
                    //}
                }

                //ssMng.CheckUss();
                lblUserName.Text = userBLL.GetUserFullNameByEmpSeq(ssMng.EmpSeqI);
                UpdateUnreadCount();
                CreatedMenu();
            }

            cmdInbox.OnClientClick = "openTaskLists('@ServerName', '@Seq')"
                .Replace("@ServerName", strServerName).Replace("@Seq", ssMng.EmpSeq);
            lbNotification.OnClientClick = "openTaskLists('@ServerName', '@Seq')"
                .Replace("@ServerName", strServerName).Replace("@Seq", ssMng.EmpSeq);
            UpdateUnreadCount();

            cmdInbox.Attributes.Add("onClick", "return false;");
            lbNotification.Attributes.Add("onClick", "return false;");

            string strControlName = ContentPlaceHolder1.Page.ToString();

            if (strControlName == "ASP.app_ui_forms_login_aspx")
            {
                RadMenu1.Visible = false;
                PanelDetail.Visible = false;
            }
            else if (strControlName == "ASP.app_ui_forms_selectsystem_aspx")
            {
                RadMenu1.Visible = false;
                PanelDetail.Visible = true;
            }
            else
            {
                RadMenu1.Visible = true;
                PanelDetail.Visible = true;
            }

            SetPageTitle("ระบบบริหารงานงบประมาณ");
        }

        public string LoadEmployees(string empSeq = null)
        {
            empSeq = empSeq ?? ssMng.EmpSeq;
            string workingJobSiteSeq = empBLL.GetWorkingJobSiteByEmpSeq(empSeq);
            return workingJobSiteSeq;
        }


        protected void cmdBackToSelectSystem_Click(object sender, EventArgs e)
        {
            Session.Abandon();
            Response.Redirect(ssMng.ServerName + ConfigurationSettings.AppSettings["SubSystemPrefix"] + "ESS/APP_UI/Forms/SelectSystem.aspx");
        }

        protected void cmdLogout_Click(object sender, EventArgs e)
        {
            HttpCookie cookie = Request.Cookies["UserDetail"];

            if (cookie != null)
            {
                cookie.Expires = DateTime.Now.AddDays(-1);
            }

            RadMenu1.Items.Clear();
            Session.Abandon();
            Response.Redirect(ssMng.ServerName + "ESS/APP_UI/Forms/Login.aspx");
        }

        private void SetPageTitle(string moduleTitle)
        {
            if (!String.IsNullOrEmpty(Page.Title)) return;
            string pageFileName = Path.GetFileName(Request.Path);
            string pageTitle = bll.GetTitlePage(pageFileName);
            pageTitle = String.IsNullOrEmpty(pageTitle) ? moduleTitle :
                String.Format("{0} - {1}", moduleTitle, pageTitle);
            Page.Title = pageTitle;
        }

        protected void UpdateUnreadCount()
        {
            int nUnreadCount = send.GetUnreadCount(ssMng.EmpSeq);
            int nOldUnreadCount = Convert.ToInt32(Session["UnreadCount"]);

            if (nUnreadCount > nOldUnreadCount)
            {
                ShowNotification(nUnreadCount);
            }

            Session["UnreadCount"] = nUnreadCount;
            lblInboxCount.Text = nUnreadCount.ToString();
        }

        protected void ShowNotification(int nUnreadCount)
        {
            lbNotification.Text = "คุณมีข้อความที่ยังไม่ได้อ่าน " + nUnreadCount.ToString();
            RadToolTip1.Show();
        }

        private void CreatedMenu()
        {
            JobSiteOption currentJobSiteOption = CheckJobSiteOption(ssMng.WorkingJobSiteSeq);
            string menusHide;
            if (currentJobSiteOption.JobSiteStrategy)
            {
                menusHide = GetLocalResourceObject("เมนูที่ซ่อนกรณีเป็นฝ่ายแผน") as string;
            }
            else
            {
                menusHide = GetLocalResourceObject("เมนูที่ซ่อนกรณีไม่ใช่ฝ่ายแผน") as string;
            }

            if (currentJobSiteOption.JobSiteOption1)
            {
                menusHide += "," + GetLocalResourceObject("เมนูที่ซ่อนเพิ่มเติมกรณีJobSiteOption1");
            }
            if (currentJobSiteOption.JobSiteOption2)
            {
                menusHide += "," + GetLocalResourceObject("เมนูที่ซ่อนเพิ่มเติมกรณีJobSiteOption2");
            }
            if (currentJobSiteOption.JobSiteOption3)
            {
                menusHide += "," + GetLocalResourceObject("เมนูที่ซ่อนเพิ่มเติมกรณีJobSiteOption3");
            }

            if (menusHide != null)
                foreach (string menuHide in menusHide.Split(','))
                {
                    if (!String.IsNullOrEmpty(menuHide))
                    {
                        HideAccess(menuHide);
                    }
                }
           
        }

        string testText = "";
        private JobSiteOption CheckJobSiteOption(string workingJobSiteSeq)
        {
            RadMenu1.DataSource = bll.LoadMenuByUsername();
            RadMenu1.DataBind();
            string strWorkingJobSiteSeq = String.IsNullOrEmpty(workingJobSiteSeq)
                ? String.Empty
                : workingJobSiteSeq;
            string jobSiteStrategy = scBLL.JobSiteStrategyID();

            testText += "," + strWorkingJobSiteSeq;
            testText += "," + workingJobSiteSeq;
            testText += "," + jobSiteStrategy;

            testText += ",[" + (strWorkingJobSiteSeq == jobSiteStrategy);
            testText += "," + strWorkingJobSiteSeq == scBLL.JobSiteOption("1"); 

            return new JobSiteOption
            {
                JobSiteStrategy = strWorkingJobSiteSeq == jobSiteStrategy || strWorkingJobSiteSeq == "127",
                JobSiteOption1 = strWorkingJobSiteSeq == scBLL.JobSiteOption("1"),
                JobSiteOption2 = strWorkingJobSiteSeq == scBLL.JobSiteOption("1"),
                JobSiteOption3 = strWorkingJobSiteSeq == scBLL.JobSiteOption("1")
            };
        }

        private class JobSiteOption
        {
            public bool JobSiteStrategy { get; set; }
            public bool JobSiteOption1 { get; set; }
            public bool JobSiteOption2 { get; set; }
            public bool JobSiteOption3 { get; set; }
        }

        private void HideAccess(string menuName)
        {
            RadMenuItem menuFound = main.FindRadMenuItemRecursive(RadMenu1, menuName);
            if (menuFound != null)
            {
                if (hideMenuBy == HideMenuBy.Color)
                    menuFound.ForeColor = Color.Red;
                if (hideMenuBy == HideMenuBy.Hide)
                    menuFound.Visible = false;
            }
        }

    }

}
